package com.fc.converters;

import javax.faces.bean.ApplicationScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.fc.entities.Recipe;
import com.fc.service.RecipeService;
import com.fc.utils.ServiceLocator;

/**
 * 
 * @author Ács Ádám
 * 
 */
@Component("recipeConverter")
@ApplicationScoped
public class RecipeConverter implements Converter {
	private RecipeService service;

	public RecipeService getService() {
		if (service == null) {
			service = ServiceLocator.getBean(RecipeService.class);
		}
		return service;
	}

	@Override
	public Recipe getAsObject(FacesContext context, UIComponent component,
			String value) {
		if (StringUtils.isBlank(value)) {
			return null;
		}

		return getService().findById(Integer.parseInt(value));
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object value) {
		if (value == null || !(value instanceof Recipe)) {
			return "";
		}
		Recipe recipe = (Recipe) value;
		return String.valueOf(recipe.getId());
	}
}
